//
//  LLComposeViewController.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/7/3.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

class LLComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
     setupUI()
    }
    
    //设置视图
    func setupUI(){
        
        //添加
        view.addSubview(textView)
        view.addSubview(toolbar)
        textView.addSubview(pictureView)
        
        
        setupNaVc()
        
        textView.backgroundColor = UIColor.whiteColor()
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        
        toolbar.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(view)
            
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView).offset(100)
            
            make.leading.equalTo(textView).offset(10)
            
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        // 弹出相册
        pictureView.composePictureViewClosure = {[weak self] ()->() in
            
            self?.selectImage()
        }
        
        
        //监听toolbar按钮的点击
        toolbar.clouser = {[weak self] (Type: LLComposeToolbarType) -> () in
            switch Type {
                
            case .Picture:
                
                self?.selectImage()
                
            case .Mention:
                print("@")
                
            case.Trend:
                
                print("#")
                
            case.Emoticon:
                print("表情")
                
                self?.switchKeyboard()
            case.Add:
                print("+")
                
                
            }
            
        }
        
        //通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //表情键盘删除按钮通知实现
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClick", name: EmoticonDeleteButtonNoti, object: nil)
        
        //表情键盘每一个按钮点击事件通知的实现
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "buttonClick:", name: EmoticonButtonNoti, object: nil)
        
    }
    func keyboardWillChangeFrame(noti: NSNotification){
        
        let rect = (noti.userInfo! ["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        
        //更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(rect.origin.y -  SCREENH)
        }
        
        UIView.animateWithDuration(0.1) { () -> Void in
            
            //更新布局
            self.view.layoutIfNeeded()
        }
    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //设置导航控制器
    func setupNaVc(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        //默认右侧发送不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
        
    }
    
    //监听事件
    //取消
    @objc func cancel(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    //删除
   func deleteButtonClick(){
    
        textView.deleteBackward()
    }
    //每一个表情按钮点击
    func buttonClick(noti: NSNotification){
        
        guard let emoticon = noti.object as? LLEmoticonBundleModel else{
            
            return
        }
        
        if emoticon.isEmoji {
            
            textView.insertText(((emoticon.code ?? "") as NSString).emoji())
        }else{
            
            let oldAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            
            let att = LLTextAttachment()
            
            att.emoticon = emoticon
            
            let path = emoticon.path ?? ""
            
            let png = emoticon.png ?? ""
            
            let name = path + png
            
            att.image = UIImage(named: name, inBundle: LLEmojiTool.sharedTool.emoticonbundle, compatibleWithTraitCollection: nil)
            
            let lineHeight = textView.font!.lineHeight
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            
             let selectRange = textView.selectedRange
            
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
             oldAttr.addAttributes([NSFontAttributeName: textView.font!], range: NSRange(location: 0, length: oldAttr.length))
            
            textView.attributedText = oldAttr
            
             textView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
             // 发送一个系统通知 隐藏或者显示textView 的站位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            // 调用代理方法使右侧按钮改变状态
            textView.delegate?.textViewDidChange!(textView)
            
            
        }
    }
    //发送
    @objc func send(){
        
        var resultStr = ""
        
        textView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: textView.attributedText.length), options: []) { (dict , range,_) -> Void in
            
            //是富文本
            if let att = dict["NSAttachment"] as? LLTextAttachment{
                
                resultStr += att.emoticon?.chs ?? ""
            }else{
                //是文字
                let name = (self.textView.attributedText.string as NSString).substringWithRange(range)
                
                resultStr += name
                
            }
        }
        if pictureView.imageList.count > 0{
           upload(resultStr)
        }else{
            // 发送文字微博
            upData(resultStr)
        }
    }
    
    //懒加载 textView
    private lazy var textView: LLComposerTextView = {
        
        let view = LLComposerTextView()
        
        view.placeholder = "请在这里输入您要发送的消息..."
        
        view.textColor = UIColor.grayColor()
        
        view.font = UIFont.systemFontOfSize(20)
        
        view.alwaysBounceVertical = true
        
        view.delegate = self
        
        return view
    }()
    
    //titleView
    private lazy var titleView: UILabel = {
       
        let lab = UILabel()
        
        //显示的名字
        let name = LLUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        
        //最终显示
        let str = "发微博\n\(name)"
        
        let attr = NSMutableAttributedString(string: str)
        
        let range = (str as NSString).rangeOfString(name)
        
        attr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:ThemeColor], range: range)
        
        lab.attributedText = attr
        
        lab.textAlignment = .Center
        
        lab.numberOfLines = 0
        
        lab.sizeToFit()
        
        return lab
        
    }()
    
    
    //懒加载toolbar
    private lazy var toolbar: LLComposeToolbar = LLComposeToolbar()
    
    //配图
    private lazy var pictureView:LLComposePictureView = LLComposePictureView()
    
    private lazy var keyboard: LLEmoticonkeyboard = {
        let view = LLEmoticonkeyboard()
        
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        
//        view.backgroundColor = UIColor.redColor()
        return view
        
    }()
}

// 发送微博
extension LLComposeViewController{
    
    //文字，无图片
    func upData(statas: String){
        
        LLNetwordTools.sharedtools.composeUpData(statas, success: { (response) -> () in
            
            print("发送成功")
            }) { (error) -> () in
                
                print("发送失败")
        }
        
    }
    //有文字有图片
    func upload(statas: String){
        LLNetwordTools.sharedtools.composeUpData(statas, imageList: pictureView.imageList, success: { (response) -> () in
            
            print("发送成功")
            }) { (error) -> () in
                
               print("发送失败")
                
        }
    }
    
}

//点击toolbar按钮事件
extension LLComposeViewController{
    
    //打开相册
    func selectImage(){
    
    let picker = UIImagePickerController()
    
        picker.delegate = self
        
    presentViewController(picker, animated: true, completion: nil)
        
        
    }
    
    //点击笑脸切换键盘
    func switchKeyboard(){
        
        if textView.inputView == nil {
            
            textView.inputView = keyboard
            
            toolbar.isEmoticon = true
            
        }else{
            
            textView.inputView = nil
            
            toolbar.isEmoticon = false
            
        }
        
        textView.reloadInputViews()
        
        textView.becomeFirstResponder()
        
    }
}

//picker 代理方法
extension LLComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //获取照片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 填充图片 调用压缩图片
        pictureView.addImages(scaleImageOfWidth(600, image: image))
        // 如果实现代理方法 系统将不再帮程序员关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)
        //方式二
//        let data = UIImageJPEGRepresentation(image, 0.2)
    }
    
    
    //方式一
    //压缩图片
    func scaleImageOfWidth(width:CGFloat,image: UIImage) ->UIImage{
        
        if width > image.size.width {
            
            return image
            
        }else{
            
            let height = (width * image.size.height) / image.size.width
            
            let rect = CGRect(x: 0, y: 0, width: width, height: height)
            
            //开启图形上下文
            UIGraphicsBeginImageContext(rect.size)
            
            //将image渲染到图形上下文
            image.drawInRect(rect)
            
            //获取
            let result = UIGraphicsGetImageFromCurrentImageContext()
            
            //关闭
            UIGraphicsEndImageContext()
            
            return result
            
            
        }
        
        
    }
}

//textView代理方法
extension LLComposeViewController: UITextViewDelegate{
    
    
    //监听textView 改变“发送”按钮状态
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    //textView滚动式是键盘退出
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        textView.resignFirstResponder()
        
    }
}
